package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.entity.*;
import com.example.demo.entity.requestJson.BuyOnrChapterReq;
import com.example.demo.entity.requestJson.DeleteReq;
import com.example.demo.entity.requestJson.QuerybuyonrChapterReq;
import com.example.demo.entity.responseJson.BuyChaptersListRes;
import com.example.demo.entity.responseJson.QuerybuyonrChapterRes;
import com.example.demo.enums.ErrCodeEnum;
import com.example.demo.mapper.*;
import com.example.demo.service.ChapterPurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 章节购买表(ChapterPurchase)Service层
 *
 * @author 杨丽辉
 * @since 2021-03-18 14:18:27
 */
@Service
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
public class ChapterPurchaseServiceImpl implements ChapterPurchaseService {
        @Autowired
        private ChapterPurchaseMapper chapterPurchaseMapper;
        @Autowired
        private ChapterMapper chapterMapper;
        @Autowired
        private WalletMapper walletMapper;
        @Autowired
        private BooksInformationMapper booksInformationMapper;
        @Autowired
        private RefundMapper refundMapper;
        @Autowired
        private UserOrderMapper userOrderMapper;


 /**
     * 通过ID和其他条件查询单条数据
     *
     * @param chapterPurchase 实例对象
     * @return 实例对象
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
     public ChapterPurchase queryChapterPurchaseLimit1(ChapterPurchase chapterPurchase){
     return  chapterPurchaseMapper.queryChapterPurchaseLimit1( chapterPurchase);
     }
     
 /**
     * 查询指定行数据
     * @param chapterPurchase 实例对象
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public   List<ChapterPurchase> queryAllChapterPurchaseByLimit( ChapterPurchase chapterPurchase, Integer offset,  Integer limit){
   return chapterPurchaseMapper.queryAllChapterPurchaseByLimit(chapterPurchase, offset,limit);
  }

  /**
     * 查询数据条数
     * @return 条数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public int countAllChapterPurchase(ChapterPurchase chapterPurchase){
   return chapterPurchaseMapper.countAllChapterPurchase( chapterPurchase);
   }
   /**
     * 通过实体作为筛选条件查询
     *
     * @param chapterPurchase 实例对象
     * @return 对象列表
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public List<ChapterPurchase> queryAllChapterPurchase(ChapterPurchase chapterPurchase){
   return chapterPurchaseMapper.queryAllChapterPurchase(chapterPurchase);
   }
  /**
     * 新增数据
     *
     * @param chapterPurchase 实例对象
     * @return 影响行数
     */
     @Override
   @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public int insertChapterPurchase(ChapterPurchase chapterPurchase){
    return  chapterPurchaseMapper.insertChapterPurchase( chapterPurchase);
    }
  /**
     * 修改数据
     *
     * @param chapterPurchase 实例对象
     * @return 影响行数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
     public  int updateChapterPurchase(ChapterPurchase chapterPurchase){
         return chapterPurchaseMapper.updateChapterPurchase( chapterPurchase);
     }

    /**
     * 通过主键删除数据
     * @param chapterPurchaseId 主键
     * @return 影响行数
     */
      @Override
  @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public  int deleteChapterPurchaseById(String chapterPurchaseId){
   return  chapterPurchaseMapper.deleteChapterPurchaseById( chapterPurchaseId);
   }
     /**
     * 通过主键列表删除，列表长度不能为0
     * @param list 集合
     * @return 条数
     */
      @Override
  @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public  int deleteChapterPurchaseByIds( List<String> list){
    return  chapterPurchaseMapper.deleteChapterPurchaseByIds(  list);
  }
    
       /**
     * 通过主键修改实体列表，列表长度不能为0，注意：当实体属性为null时，对应的列也会别更新为null
     * @param list 集合
     * @return 条数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public int updateChapterPurchaseBatch( List<ChapterPurchase> list){
   return  chapterPurchaseMapper.updateChapterPurchaseBatch(list);
   }
    /**
     * 批量其他列,除主键以外的列，列表长度不能为0,字段是空的就置为null
     * @param list 集合
     * @return 条数
     */
      @Override
  @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
 public   int insertChapterPurchaseBatch( List<ChapterPurchase> list){
 return chapterPurchaseMapper.insertChapterPurchaseBatch( list);
 }
      /**
     * 通过实体非空属性删除
     * @param chapterPurchase  实体
     * @return 条数
     */
        @Override
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public   int deleteChapterPurchaseByEntity( ChapterPurchase chapterPurchase){
  return  chapterPurchaseMapper.deleteChapterPurchaseByEntity(  chapterPurchase);
  }
    /**
     * 通过实体不为空的属性作为筛选条件查询列表
     * @param chapterPurchase  实体
     * @return list
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public  List<ChapterPurchase> listChapterPurchaseByEntity(ChapterPurchase chapterPurchase){
   return chapterPurchaseMapper.listChapterPurchaseByEntity( chapterPurchase);
   }

 /**
     * 新增实体属性不为null的列
     * @param chapterPurchase  实体
     * @return 条数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public  int insertChapterPurchaseSelect( ChapterPurchase chapterPurchase){
      return chapterPurchaseMapper.insertChapterPurchaseSelect( chapterPurchase);

   }
   
      /**
     * 批量新增新增实体属性不为null的列
     * @param list  实体
     * @return 条数
     */
        @Override
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public  int insertChapterPurchaseListSelect( List<ChapterPurchase> list){

     return chapterPurchaseMapper.insertChapterPurchaseListSelect( list);
      }
     /**
     * 通过实体不为空的属性作为筛选条件查询单个
     * @param chapterPurchase  实体
     * @return 单个
     */
     @Override
   @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public  ChapterPurchase getChapterPurchaseByEntity(ChapterPurchase chapterPurchase){
     return  chapterPurchaseMapper.getChapterPurchaseByEntity(chapterPurchase);
    }

    /**
     * 批量订阅查询所有付费章节
     * 1.点击批量查询按钮，返回章节名和所需积分
     */
    @Override
    public BackResponseEntity<List<BuyChaptersListRes>> querybuyChaptersListRes(DeleteReq deleteReq){
        LambdaQueryWrapper<Chapter> wrapper = new QueryWrapper<Chapter>().lambda();
        wrapper.select(Chapter::getChapterName,Chapter::getChapterPoints)
                .eq(Chapter::getBookId,deleteReq.getId())
                .eq(Chapter::getIsFree,1);

        List<Chapter> list = chapterMapper.selectList(wrapper);
        List presenter = list;
        List<BuyChaptersListRes> res1 = presenter;

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, res1, "");
    }

    /**
     * 单章节购买查询
     * 1.返回所消耗积分和用户目前剩余积分
     * */
    @Override
    public BackResponseEntity<QuerybuyonrChapterRes> querybuyOneChaptersRes(QuerybuyonrChapterReq querybuyonrChapterReq){
        Wallet wallet = new Wallet();
        wallet.setUserId(querybuyonrChapterReq.getUserId());
        Wallet wallet1 = walletMapper.queryWalletLimit1(wallet);
        Chapter chapter = chapterMapper.selectById(querybuyonrChapterReq.getChapterId());

        QuerybuyonrChapterRes querybuyonrChapterRes = new QuerybuyonrChapterRes();
        querybuyonrChapterRes.setBookId(chapter.getBookId());
        querybuyonrChapterRes.setConsumptionPoints(chapter.getChapterPoints());
        querybuyonrChapterRes.setCatfoodCount(wallet1.getCatfoodCount());

        return BackResponseEntity.success(ErrCodeEnum.unknown_0,querybuyonrChapterRes,"");
    }

    /**
     * 单章节购买
     * 1.传userId
     * 2.购买成功，在章节购买记录表，订单表中插入相应记录，钱包对应积分减少，可以查看内容
     * 3.购买失败
     * 3.1.用户积分扣除，作者积分未到账
     * 3.1.1.将记录插入到订单表，退款记录表，用户积分回复原样
     * 3.2.用户积分未扣除，作者收入增加
     * 3.2.1.将记录插入到订单表，退款记录表，作者收到的收入减去
     * */
    @Override
    public BackResponseEntity<Object> buyOneChapter(BuyOnrChapterReq buyOnrChapterReq){
        BooksInformation booksInformation = booksInformationMapper.selectById(buyOnrChapterReq.getBookId());
        Chapter chapter = chapterMapper.selectById(buyOnrChapterReq.getChapterId());
        String walletId = chapterPurchaseMapper.queryWalletId(Wrappers.<Wallet>query().eq("user_id",buyOnrChapterReq.getUserId()));
        int count = chapterPurchaseMapper.queryCatfood(Wrappers.<Wallet>query().eq("user_id",buyOnrChapterReq.getUserId()));

        if(count < buyOnrChapterReq.getConsumptionPoints()){
            return BackResponseEntity.success(ErrCodeEnum.unknown_1049, "主子您猫粮不足啦！");
        }

        int catfood =  count - buyOnrChapterReq.getConsumptionPoints();
        Wallet wallet = new Wallet();
        wallet.setWalletId(walletId);
        wallet.setCatfoodCount(catfood);
        int i = walletMapper.updateWallet(wallet);

        String authorwalletId = chapterPurchaseMapper.queryWalletId(Wrappers.<Wallet>query().eq("user_id",booksInformation.getAuthorId()));
        BigDecimal income = chapterPurchaseMapper.queryIncom(Wrappers.<Wallet>query().eq("user_id",booksInformation.getAuthorId()));
        Wallet wallet5 = new Wallet();
        wallet5.setWalletId(authorwalletId);
        BigDecimal res = BigDecimal.valueOf(buyOnrChapterReq.getConsumptionPoints()/10.0);
        wallet5.setIncome(income.add(res));

        int m = walletMapper.updateWallet(wallet5);


        ChapterPurchase chapterPurchase = new ChapterPurchase();
        chapterPurchase.setChapterId(buyOnrChapterReq.getChapterId());
        chapterPurchase.setChapterName(chapter.getChapterName());
        chapterPurchase.setBookId(buyOnrChapterReq.getBookId());
        chapterPurchase.setBookName(booksInformation.getBookName());
        chapterPurchase.setAuthorId(booksInformation.getAuthorId());
        chapterPurchase.setUserId(buyOnrChapterReq.getUserId());
        chapterPurchase.setConsumptionPoints(buyOnrChapterReq.getConsumptionPoints());
        chapterPurchase.setCreateTime(LocalDateTime.now());


        if(i > 0 && m <= 0){
            Wallet wallet1 = new Wallet();
            wallet1.setWalletId(walletId);
            wallet1.setCatfoodCount(count+ buyOnrChapterReq.getConsumptionPoints());

            walletMapper.updateWallet(wallet);
            chapterPurchase.setIsBuy(1);
            chapterPurchaseMapper.insert(chapterPurchase);

            chapterPurchase.setChapterId(buyOnrChapterReq.getChapterId());
            ChapterPurchase chapterPurchase1 = chapterPurchaseMapper.queryChapterPurchaseLimit1(chapterPurchase);

            UserOrder order = new UserOrder();
            order.setUserId(buyOnrChapterReq.getUserId());
            order.setCommodityCount(1);
            order.setConsumptionPoints(buyOnrChapterReq.getConsumptionPoints());
            order.setOrderExplain("单章节购买");
            order.setStatus(2);
            order.setOrderType(0);
            order.setCreateTime(LocalDateTime.now());
            order.setTargetId(chapterPurchase1.getChapterPurchaseId());

            userOrderMapper.insert(order);

            Refund refund = new Refund();
            UserOrder order1 = new UserOrder();
            order1.setTargetId(chapterPurchase1.getChapterPurchaseId());
            UserOrder order2 = userOrderMapper.getUserOrderByEntity(order1);

            refund.setUserId(buyOnrChapterReq.getUserId());
            refund.setOrderId(order2.getOrderId());
            refund.setRefundType(1);
            refund.setRefundCatfood(order2.getConsumptionPoints());
            refund.setIsRefund(0);
            refund.setCreateTime(LocalDateTime.now());

            refundMapper.insert(refund);

            return BackResponseEntity.success(ErrCodeEnum.unknown_1050, "购买失败");
        }
        if(i < 0 && m > 0){
            Wallet wallet1 = new Wallet();
            wallet1.setWalletId(authorwalletId);
            wallet1.setIncome(income.subtract(BigDecimal.valueOf(buyOnrChapterReq.getConsumptionPoints()/10)));

            walletMapper.updateWallet(wallet);
            chapterPurchase.setIsBuy(1);
            chapterPurchaseMapper.insert(chapterPurchase);

            chapterPurchase.setChapterId(buyOnrChapterReq.getChapterId());
            ChapterPurchase chapterPurchase1 = chapterPurchaseMapper.queryChapterPurchaseLimit1(chapterPurchase);

            UserOrder order = new UserOrder();
            order.setUserId(buyOnrChapterReq.getUserId());
            order.setCommodityCount(1);
            order.setConsumptionPoints(buyOnrChapterReq.getConsumptionPoints());
            order.setOrderExplain("单章节购买");
            order.setStatus(2);
            order.setOrderType(0);
            order.setCreateTime(LocalDateTime.now());
            order.setTargetId(chapterPurchase1.getChapterPurchaseId());

            userOrderMapper.insert(order);

            Refund refund = new Refund();
            UserOrder order1 = new UserOrder();
            order1.setTargetId(chapterPurchase1.getChapterPurchaseId());
            UserOrder order2 = userOrderMapper.getUserOrderByEntity(order1);

            refund.setUserId(buyOnrChapterReq.getUserId());
            refund.setOrderId(order2.getOrderId());
            refund.setRefundType(1);
            refund.setRefundCatfood(order2.getConsumptionPoints());
            refund.setIsRefund(0);
            refund.setCreateTime(LocalDateTime.now());

            refundMapper.insert(refund);

            return BackResponseEntity.success(ErrCodeEnum.unknown_1050, "购买失败");
        }

        chapterPurchase.setIsBuy(0);
        chapterPurchaseMapper.insert(chapterPurchase);

        chapterPurchase.setChapterId(buyOnrChapterReq.getChapterId());
        ChapterPurchase chapterPurchase1 = chapterPurchaseMapper.queryChapterPurchaseLimit1(chapterPurchase);

        UserOrder order = new UserOrder();
        order.setUserId(buyOnrChapterReq.getUserId());
        order.setCommodityCount(1);
        order.setConsumptionPoints(buyOnrChapterReq.getConsumptionPoints());
        order.setOrderExplain("单章节购买");
        order.setStatus(0);
        order.setOrderType(0);
        order.setCreateTime(LocalDateTime.now());
        order.setTargetId(chapterPurchase1.getChapterPurchaseId());

        userOrderMapper.insert(order);

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, "购买成功");

    }
}

